package com.swak.consistency.core.resolve.impls;

import java.util.Comparator;
import java.util.List;

import com.swak.consistency.core.attribute.ConsistencyAttribute;
import com.swak.consistency.core.context.ConsistencyContext;
import com.swak.consistency.core.execption.ConsistencyException;
import com.swak.consistency.core.resolve.ContextResolver;
import com.swak.utils.Lists;

/**
 * 多种获取方式
 * 
 * @author DELL
 */
public abstract class MultiResolver<T extends ConsistencyContext>
		implements ContextResolver<T>, Comparator<ContextResolver<T>> {

	List<ContextResolver<T>> resolvers = Lists.newArrayList();

	public MultiResolver<T> addResolver(ContextResolver<T> resolver) {
		this.resolvers.add(resolver);
		return this.sort();
	}

	public MultiResolver<T> addResolvers(List<ContextResolver<T>> resolvers) {
		this.resolvers.addAll(resolvers);
		return this.sort();
	}

	protected MultiResolver<T> sort() {
		this.resolvers.sort(this);
		return this;
	}

	@Override
	public T acquire(ConsistencyAttribute attribute) {
		for (ContextResolver<T> acquire : resolvers) {
			if (acquire.support(attribute.getScheme())) {
				T context = acquire.acquire(attribute);
				if (context != null) {
					return context;
				}
			}
		}
		throw new ConsistencyException("请指定一个事务的实现机制");
	}
	
	@Override
	public T create(ConsistencyAttribute attribute) {
		for (ContextResolver<T> acquire : resolvers) {
			if (acquire.support(attribute.getScheme())) {
				T context = acquire.create(attribute);
				if (context != null) {
					return context;
				}
			}
		}
		throw new ConsistencyException("请指定一个事务的实现机制");
	}

	@Override
	public void transmit(T context) {
		for (ContextResolver<T> acquire : resolvers) {
			if (acquire.support(context.getScheme())) {
				acquire.transmit(context);
			}
		}
	}

	@Override
	public int compare(ContextResolver<T> o1, ContextResolver<T> o2) {
		return o1.getOrder() >= o2.getOrder() ? 0 : 1;
	}
}
